import * as BABYLON from "babylonjs";

export class Hit3D {
    private _canvas: HTMLCanvasElement;
    private _engine: BABYLON.Engine;
    private _scene: BABYLON.Scene;
    private _camera: BABYLON.FreeCamera;
    private _light: BABYLON.Light;
    constructor(canvasId: string) {
        this._canvas = document.getElementById(canvasId) as HTMLCanvasElement;
        this._engine = new BABYLON.Engine(this._canvas, true);
        this._scene = {} as BABYLON.Scene;
        this._camera = {} as BABYLON.FreeCamera;
        this._light = {} as BABYLON.Light;
    }

    createScene(): void {
        this._scene = new BABYLON.Scene(this._engine);
        this._scene.ambientColor = new BABYLON.Color3(1, 1, 1); // 设置背景颜色
        this._camera = new BABYLON.FreeCamera('mycamera', new BABYLON.Vector3(0, 5, -5), this._scene);
        this._camera.setTarget(BABYLON.Vector3.Zero());
        this._camera.attachControl(this._canvas, false);
        this._light = new BABYLON.HemisphericLight('mylight', new BABYLON.Vector3(0, 1, 0), this._scene);
    }

    createShape() {
        // 1. 普通碰撞
        // 地面
        let ground = BABYLON.Mesh.CreatePlane('ground', 20.0, this._scene);
        let groundmat = new BABYLON.StandardMaterial('groundmat', this._scene);
        groundmat.diffuseColor = BABYLON.Color3.Green();
        groundmat.backFaceCulling = false;
        ground.material = groundmat;
        ground.position = new BABYLON.Vector3(0, -3, 0);
        ground.rotation = new BABYLON.Vector3(Math.PI / 2, 0, 0);

        // 物体
        let box = BABYLON.Mesh.CreateBox("Box1", 1, this._scene);
        box.checkCollisions = true;
        let boxmat: BABYLON.StandardMaterial = new BABYLON.StandardMaterial('boxmat', this._scene);
        boxmat.diffuseColor = new BABYLON.Color3(0.7, 0.5, 0.7);
        box.material = boxmat;
        box.position = new BABYLON.Vector3(0, -2, 0);

        // 定义重力
        this._scene.gravity = new BABYLON.Vector3(0, -9.18, 0);
        this._camera.applyGravity = true;

        // 启用碰撞
        this._scene.collisionsEnabled = true;
        this._camera.checkCollisions = true;

        // 定义椭圆体
        this._camera.ellipsoid = new BABYLON.Vector3(1, 1, 1);
        // 设置物体碰撞
        ground.checkCollisions = true;
        box.checkCollisions = true;

    }

    async animationExecution(animatable) {
        console.log('begin ... ');
        await animatable.waitAsync();
        console.log('after ...')
    }

    doRender(): void {
        // Run the render loop.
        this._engine.runRenderLoop(() => {
            this._scene.render();
        });

        // The canvas/window resize event handler.
        window.addEventListener('resize', () => {
            this._engine.resize();
        });
    }
}